#include "sm3.h"
#include "common_func.h"
#include "core_time.h"
#include <string.h>

uint32_t sm3_init(SM3_Handle_t *session_handle)
{
	// module not ready for input
	if(RegRead(SM3_MSG_INPT_RDY) == 0x00)
	{
		return 0x01;
	}
	//clear
	//memset(session_handle, 0x0, sizeof(SM3_Handle_t));
	//set flag
	session_handle->init_flag = 0x1;
	session_handle->first_data_flag = 0x1;
	
	return 0;
}

uint32_t sm3_update(SM3_Handle_t *session_handle, uint32_t data)
{
	//不按顺序调用
	if(session_handle->init_flag != 0x1)
	{
		return 0x02;
	}
	
	//首数据不执行发送
	if(session_handle->first_data_flag == 0x1)
	{
		session_handle->first_data_flag = 0x0;
		session_handle->update_flag = 0x1;
	}
	//发送上一数据
	else
	{
		RegWrite(SM3_MSG_INPT_D, session_handle->data);
		RegWrite(SM3_MSG_INPT_VLD_BYTE, 0xF);
		RegWrite(SM3_MSG_INPT_VLD, 0x1);
	}
	
	//缓存数据
	session_handle->data = data;
	
	return 0;
}

uint32_t sm3_final(SM3_Handle_t *session_handle, uint32_t *result_data)
{
	//不按顺序调用
	if(session_handle->update_flag != 0x1)
	{
		return 0x02;
	}
	
	//写入最后数据
	RegWrite(SM3_MSG_INPT_D, session_handle->data);
	RegWrite(SM3_MSG_INPT_VLD_BYTE, 0xF);
	RegWrite(SM3_MSG_INPT_LST, 0x1);
	RegWrite(SM3_MSG_INPT_VLD, 0x1);
	
	//wait result
	while(RegRead(SM3_CMPRSS_OTPT_VLD) == 0x00)
	{
		delay_ms(SM3_WAIT_TIME);
	}
	
	//获取结果
	result_data[0] = RegRead(SM3_CMPRSS_OTPT_RES_0);
	result_data[1] = RegRead(SM3_CMPRSS_OTPT_RES_1);
	result_data[2] = RegRead(SM3_CMPRSS_OTPT_RES_2);
	result_data[3] = RegRead(SM3_CMPRSS_OTPT_RES_3);
	result_data[4] = RegRead(SM3_CMPRSS_OTPT_RES_4);
	result_data[5] = RegRead(SM3_CMPRSS_OTPT_RES_5);
	result_data[6] = RegRead(SM3_CMPRSS_OTPT_RES_6);
	result_data[7] = RegRead(SM3_CMPRSS_OTPT_RES_7);
	
	//清理
	RegWrite(SM3_MSG_INPT_LST, 0x0);
	
	return 0;
}

uint32_t sm3_final_int(SM3_Handle_t *session_handle)
{
	//不按顺序调用
	if(session_handle->update_flag != 0x1)
	{
		return 0x02;
	}

	RegWrite(0xbf20f004, 0x40);//edge	边沿
	RegWrite(0xbf20f008, 0x40);//pol  高电平
	RegWrite(0xbf20f00c, 0x40);//clr
	RegWrite(0xbf20f000, 0x40);//en
	RegWrite(SM3_ENABLE_INT, 0x1);//en

	//写入最后数据
	RegWrite(SM3_MSG_INPT_D, session_handle->data);
	RegWrite(SM3_MSG_INPT_VLD_BYTE, 0xF);
	RegWrite(SM3_MSG_INPT_LST, 0x1);
	RegWrite(SM3_MSG_INPT_VLD, 0x1);
	
	//清理
	RegWrite(SM3_MSG_INPT_LST, 0x0);

	return 0;
}

uint32_t sm3_callback(uint32_t *result_data)
{
	//获取结果
	result_data[0] = RegRead(SM3_CMPRSS_OTPT_RES_0);
	result_data[1] = RegRead(SM3_CMPRSS_OTPT_RES_1);
	result_data[2] = RegRead(SM3_CMPRSS_OTPT_RES_2);
	result_data[3] = RegRead(SM3_CMPRSS_OTPT_RES_3);
	result_data[4] = RegRead(SM3_CMPRSS_OTPT_RES_4);
	result_data[5] = RegRead(SM3_CMPRSS_OTPT_RES_5);
	result_data[6] = RegRead(SM3_CMPRSS_OTPT_RES_6);
	result_data[7] = RegRead(SM3_CMPRSS_OTPT_RES_7);
}


